package threadPool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-19 19:45
 **/
public class T05_MyExecutionHandler {

    static class MyService implements Runnable {
        private String MSG = "由我来处理吧！";
        private Integer i;

        public MyService(Integer i) {
            this.i = i;
        }

        @Override
        public void run() {
            try {
                System.err.println(Thread.currentThread().getName() + " thread --->" + i);
                System.in.read();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "MyService{i=" + i + "}";
        }
    }

    static class MyExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            if (r instanceof MyService) {
                System.err.println(" thread --->" + Thread.currentThread().getName());
                MyService myService = (MyService) r;
                System.err.println(myService.MSG);
            }
        }
    }

    static class MyRunnable {

        public static void main(String[] args) {
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new MyExecutionHandler());
            for (int i = 0; i < 8; i++) {
                threadPoolExecutor.execute(new MyService(i));
            }
            threadPoolExecutor.execute(new MyService(100));
            System.err.println(threadPoolExecutor.getQueue());
            threadPoolExecutor.shutdown();
        }


    }
}
